@extends('layouts.app')

@section('content')
<!-- 添加这个错误处理部分 -->
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- 确保 CSRF token 在 head 中 -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Register') }}</div>

                <div class="card-body">
                    <!-- 第一步：邮箱验证表单 -->
                    <form id="emailForm" class="step-form" style="display: block;" onsubmit="return false;">
                        @csrf
                        <div class="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>
                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" 
                                    name="email" value="{{ old('email') }}" required autocomplete="email">
                                <small id="emailHelp" class="form-text text-muted">请输入有效的邮箱地址</small>
                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <!-- 验证码输入框，默认隐藏 -->
                        <div class="row mb-3" id="verificationCodeDiv" style="display: none;">
                            <label for="code" class="col-md-4 col-form-label text-md-end">验证码</label>
                            <div class="col-md-6">
                                <input id="code" type="text" class="form-control" name="code">
                                <small class="form-text text-muted">请输入发送到您邮箱的验证码</small>
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="button" class="btn btn-primary" id="nextStepBtn">
                                    {{ __('Next Step') }}
                                </button>
                                <span id="countdownText" class="ml-2" style="display: none;"></span>
                                <button type="button" class="btn btn-success" id="verifyCodeBtn" style="display: none;">
                                    验证
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- 第二步：完整注册表单，默认隐藏 -->
                    <form id="registerForm" method="POST" action="{{ route('register.complete') }}" style="display: none;">
                        @csrf
                        <input type="hidden" name="email" id="finalEmail">
                        
                        <!-- 显示已验证的邮箱 -->
                        <div class="row mb-3">
                            <label class="col-md-4 col-form-label text-md-end">已验证邮箱</label>
                            <div class="col-md-6">
                                <p class="form-control-static" id="displayEmail" style="padding-top: 7px;"></p>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="name" class="col-md-4 col-form-label text-md-end">{{ __('Name') }}</label>
                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" 
                                    name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
                                <small class="form-text text-muted">请输入您的昵称</small>
                                @error('name')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>
                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" 
                                    name="password" required autocomplete="new-password">
                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-end">
                                {{ __('Confirm Password') }}
                            </label>
                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" 
                                    name="password_confirmation" required autocomplete="new-password">
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Register') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    console.log('Script section loaded');
    
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM Content Loaded');
        
        const nextStepBtn = document.getElementById('nextStepBtn');
        const verifyCodeBtn = document.getElementById('verifyCodeBtn');
        
        console.log('Found nextStepBtn:', nextStepBtn);

        if (nextStepBtn) {
            nextStepBtn.addEventListener('click', handleNextStep);
            console.log('Added click event listener to nextStepBtn');
        }

        if (verifyCodeBtn) {
            verifyCodeBtn.addEventListener('click', handleVerifyCode);
            console.log('Added click event listener to verifyCodeBtn');
        }
    });

    function handleNextStep(e) {
        e.preventDefault();
        console.log('Next Step button clicked');

        const email = document.getElementById('email').value;
        console.log('Email entered:', email);

        // 获取 CSRF token
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        console.log('CSRF Token:', token);

        // 发送请求
        fetch('{{ route("verification.send") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': token,
                'Accept': 'application/json'
            },
            body: JSON.stringify({ email: email })
        })
        .then(response => {
            console.log('Raw response:', response);
            return response.json();
        })
        .then(data => {
            console.log('Response data:', data);
            if (data.success) {
                alert('验证码已发送，请查收邮件');
                
                // 显示验证码输入框
                document.getElementById('verificationCodeDiv').style.display = 'flex';
                // 隐藏发送按钮
                document.getElementById('nextStepBtn').style.display = 'none';
                // 显示验证按钮
                document.getElementById('verifyCodeBtn').style.display = 'inline-block';
            } else {
                alert(data.message || '发送失败，请重试');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('发送失败：' + error.message);
        });
    }

    // 添加验证码验证函数
    function handleVerifyCode(e) {
        e.preventDefault();
        console.log('Verify button clicked');

        const email = document.getElementById('email').value;
        const code = document.getElementById('code').value;
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        if (!code) {
            alert('请输入验证码');
            return;
        }

        fetch('{{ route("register.verify-code") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': token,
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                code: code
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Verification response:', data);
            if (data.success) {
                // 验证成功，显示注册表单
                document.getElementById('emailForm').style.display = 'none';
                document.getElementById('registerForm').style.display = 'block';
                
                // 设置邮箱
                document.getElementById('finalEmail').value = email;
                document.getElementById('displayEmail').textContent = email;
            } else {
                alert(data.message || '验证码错误');
            }
        })
        .catch(error => {
            console.error('Verification error:', error);
            alert('验证失败：' + error.message);
        });
    }
</script>
@endpush
